/**
 * 
 */
package freedom.needle.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.log.MLog;
import com.mchange.v2.log.MLogger;

/**
 * @author charlie
 *
 */
public class DataSourceFactory {
	final static MLogger logger = MLog.getLogger(DataSourceFactory.class);

	private static ComboPooledDataSource dataSource = null;
	
	public static DataSource getDataSource() {
		if(dataSource == null)
			initDataSource();
		return dataSource;
	}
	
	private static synchronized void initDataSource() {
		if(dataSource == null)
			dataSource = new ComboPooledDataSource("mysql");
	}

	/**
	 * 获得数据库连接
	 * 
	 * @return Connection
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException {
		return getDataSource().getConnection();
	}

	/**
	 * 数据库关闭操作
	 * 
	 * @param conn
	 * @param st
	 * @param pst
	 * @param rs
	 */
	public static void close(Connection conn, PreparedStatement pst, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pst != null) {
			try {
				pst.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 测试DBUtil类
	 * 
	 * @param args
	 * @throws SQLException 
	 */
	public static void main(String[] args) throws SQLException {

		Connection conn = getConnection();
		System.out.println(conn.getClass().getName());
		close(conn, null, null);
	}
}
